﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Core.Model;
using EzDesk.Core.CoreImpl.Repositories.Interface;

namespace EzDesk.Core.CoreImpl.Repositories
{
    public class AppRepository : IAppRepository, IRepository<App>
    {
        private EzDeskDataContext _db;

        public AppRepository(EzDeskDataContext db)
        {
            _db = db;
        }

        //todo: 使用DI重构
        public AppRepository()
            : this(new EzDeskDataContext())
        { }


        #region IRepository<App> Members

        public void SaveChanges()
        {
            _db.SubmitChanges();
        }

        public Guid Add(App model, bool saveChanges = true)
        {
            var entity = model.ToEntity();
            _db.ez_Apps.InsertOnSubmit(entity);

            if (saveChanges)
            {
                SaveChanges();
            }
            return entity.AppId;
        }

        public App GetById(Guid id)
        {
            App app = null;
            if (id != null)
            {
                app = _db.ez_Apps.Where(p => p.AppId == id)
                    .SingleOrDefault()
                    .ToModel();
            }
            return app;
        }

        public IQueryable<App> GetAll()
        {
            return _db.ez_Apps.Select(
                p => new App()
                {
                    Id = p.AppId,
                    Name = p.Name,
                    Description = p.Description,
                    Title = p.Title,
                });
        }

        public void Delete(Guid id, bool saveChanges = true)
        {
            var entity = _db.ez_Apps.Where(p => p.AppId == id)
                .SingleOrDefault();
            _db.ez_Apps.DeleteOnSubmit(entity);
            if (saveChanges)
            {
                SaveChanges();
            }
        }

        public void Update(App model, bool saveChanges = true)
        {
            var entity = _db.ez_Apps.Where(p => p.AppId == model.Id)
                .SingleOrDefault();
            ModelConvert.CopyValueApp(entity, model);
            if (saveChanges)
            {
                SaveChanges();
            }
        }

        #endregion


        public App GetAppByName(string appName)
        {
            App app = null;
            var entiry = _db.ez_Apps.Where(p => p.Name == appName).SingleOrDefault();
            if (entiry != null)
            {
                app = entiry.ToModel();
            }
            return app;
        }
    }
}
